package com.woniuxy.goods.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class PermissionFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //拦截请求  先获取 request对象
        ServerHttpRequest request = exchange.getRequest();
        //获取token
        String token = request.getQueryParams().getFirst("token");

        if (token != null) {
            // 解析 token   合法 登录   不合法  伪造的token

            //方形
            //向请求对象中添加header
            request = exchange.getRequest().mutate().header("token", token).build();

           return chain.filter(exchange.mutate().request(request).build());
        }else {
            //没有登录

            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete() ;
        }

    }

    /**
     * 过滤器的执行顺序  数字越小  优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
